﻿#include "PropertyPage.h"
#include <qapplication.h>
#include <qstyle.h>
#include <QIcon>
#include <qdebug.h>
#include <qvalidator.h>
#include <system_error>
#include "FileBuffSystem.h"
#include "PropertyItem.h"
using namespace widgetUI;

void PropertyPage::activation(QObject* obj
	, int index
	, EVENTFLAG status) {
	qDebug( ) << getName( );
}

void PropertyPage::setFilePath(const QString& filePath) {
	this->currentFilePath = filePath;
}

void PropertyPage::initControl( ) {
	mainLayout = qobject_cast<QVBoxLayout*>(ui.areaCon->layout( ));
	this->xmlDataUnit = new dXml::XmlDataUnit;
	QRegExp regExp("^\\d+$"); //创建了一个模式
	QRegExpValidator* pattern = new QRegExpValidator(regExp, this); //创建了一个表达式
	ui.infoName->setValidator(pattern);
	ui.proEdit->setValidator(pattern);
	connect(ui.synInfo, &QPushButton::clicked, this, &PropertyPage::synInfo);
	connect(ui.updateTransl, &QPushButton::clicked, this, &PropertyPage::translating);
	connect(ui.creatorInfo, &QPushButton::clicked, this, &PropertyPage::newInfo);
	connect(ui.saveFileInfoList, &QPushButton::clicked, this, &PropertyPage::saveToList);
	connect(ui.saveFile, &QPushButton::clicked, this, &PropertyPage::saveToFile);
	connect(ui.proEdit, &QLineEdit::textChanged, this, &PropertyPage::textChanged);
}

void PropertyPage::test( ) {
	for( int i = 0;i < 100;++i ) {
		PropertyItem* propertyItem = new PropertyItem(this);
		mainLayout->insertWidget(0, propertyItem);
	}
}

void PropertyPage::connectPropertyItem(PropertyItem* propertyItem) {
	connect(propertyItem, &PropertyItem::editBtnSig, this, &PropertyPage::editItem);
	connect(propertyItem, &PropertyItem::removeBtnSig, this, &PropertyPage::removeItem);
}

void PropertyPage::xmlToItem(const QList<dXml::XmlDataUnit*>& list) {
	this->xmlDataUnit->clear( );
	this->xmlDataUnit->setName(nodeName);
	for( auto& node : list ) {
		QList<dXml::XmlDataUnit*>* list = node->getChildrens( );
		QList<dXml::XmlDataUnit*>::iterator iterator = list->begin( );
		QList<dXml::XmlDataUnit*>::iterator end = list->end( );
		for( ;iterator != end;++iterator ) {
			dXml::XmlDataUnit* unit = *iterator;
			xmlDataUnit->appendChildren(unit);
			PropertyItem* propertyItem = new PropertyItem(this);
			mainLayout->insertWidget(0, propertyItem);
			QString nodeCode = unit->nodeName( ).remove("node_");
			QString value = unit->getText( );
			// todo:去掉多余 0

			QString removeZero = value.remove(removePreZero);
			if( removeZero.isEmpty( ) )
				value = "0";
			else
				value = removeZero;
			const QString tran = unit->getAttrs( )->value(widgetUI::MainWindow::getMenuPage( )->translatingToolPage->getName( ));
			propertyItem->number->setText(nodeCode);
			propertyItem->property->setText(value);
			propertyItem->Translation->setText(tran);
			itemArray->append(propertyItem);
			connectPropertyItem(propertyItem);
		}
	}
}

void PropertyPage::clear( ) {
	currentEditItem = Q_NULLPTR;
	xmlDataUnit->clear( );
	QVector<PropertyItem*>::iterator iterator = itemArray->begin( );
	QVector<PropertyItem*>::iterator end = itemArray->end( );
	for( ;iterator != end;++iterator ) {
		PropertyItem* widget = *iterator;
		delete widget;
		mainLayout->removeWidget(widget);
	}
	itemArray->clear( );
}

void PropertyPage::synInfo(bool clicked) {
	dXml::XmlDataDoc doc = appInstances::FileBuffSystem::fileInstance.getDocValue(this->currentFilePath);
	QList<dXml::XmlDataUnit*> units = doc.findChildrens(nodeName);
	clear( );
	xmlToItem(units);
	sortItem( );
}

void PropertyPage::sortItem( ) {
	qSort(itemArray->begin( ), itemArray->end( ), &PropertyPage::sortFun);
	QVector<PropertyItem*>::iterator iterator = itemArray->begin( );
	QVector<PropertyItem*>::iterator end = itemArray->end( );
	for( ;iterator != end;++iterator ) {
		mainLayout->removeWidget(*iterator);
	}
	iterator = itemArray->begin( );
	for( ;iterator != end;++iterator ) {
		mainLayout->insertWidget(0, *iterator);
	}
}

bool PropertyPage::sortFun(PropertyItem* left
	, PropertyItem* right) {
	if( left->number->text( ).toInt( ) < right->number->text( ).toInt( ) )
		return false;
	return true;
}

void PropertyPage::newInfo(bool clicked) {
	int length = itemArray->length( );
	int newNumber = -1;
	QString buffStr("%1");
	QString comStr;
	bool noHave;
	do {
		noHave = false;
		newNumber++;
		comStr = buffStr.arg(newNumber);
		for( int index = 0;index < length;++index ) {
			QString text = itemArray->at(index)->number->text( );
			if( comStr == text )
				noHave = true;
		}
	} while( noHave );
	PropertyItem* item = new PropertyItem(this);
	connectPropertyItem(item);
	item->number->setText(comStr);
	itemArray->append(item);
	dXml::XmlDataUnit* nUnit = new dXml::XmlDataUnit;
	nUnit->setName("node_" + comStr);
	nUnit->setText("0");
	xmlDataUnit->appendChildren(nUnit);
	saveToFileSystemBuff( );
	sortItem( );
}

void PropertyPage::saveToFileSystemBuff( ) {
	dXml::XmlDataDoc doc = appInstances::FileBuffSystem::fileInstance.getDocValue(currentFilePath);
	dXml::XmlDataUnit* dataUnit = new dXml::XmlDataUnit(*xmlDataUnit);
	QList<dXml::XmlDataUnit*> list = doc.findChildrens(dataUnit->nodeName(  ));
	auto && iterator = list.begin(  );
	auto && end = list.end(  );
	for(;iterator!=end;++iterator) {
		dXml::XmlDataUnit* unit = *iterator;
		unit->setParen(Q_NULLPTR);
		delete unit;
	}
	doc.appendChildren(dataUnit);
	appInstances::FileBuffSystem::fileInstance.insertMapUnity(currentFilePath, doc);
}

void PropertyPage::saveToItem(QString text
	, QString number) {
	dXml::XmlDataUnit* xml = xmlDataUnit->findChildren("node_" + number);
	xml->setText(text);
	xml->appendAttr(widgetUI::MainWindow::getMenuPage( )->translatingToolPage->getName( ), currentEditItem->Translation->text( ));
}

void PropertyPage::saveToList(bool clicked) {
	while( !noSaveArray->isEmpty( ) ) {
		PropertyItem* item = noSaveArray->last( );
		item->status->setText("保存完毕");
		QString text = item->property->text( );
		QString number = item->number->text( );
		saveToItem(text, number);
		noSaveArray->removeLast( );
	}
	if( currentEditItem != Q_NULLPTR ) {
		QString text = ui.proEdit->text( ).remove(removePreZero);
		ui.proEdit->setText(text);
		currentEditItem->property->setText(text);
		currentEditItem->status->setText("正在编辑(已经保存当前状态)");
		QString number = currentEditItem->number->text( );
		saveToItem(text, number);
	}
	saveToFileSystemBuff( );
}

inline void widgetUI::PropertyPage::textChanged(const QString& text) {
	if( currentEditItem )
		if( currentEditItem->property->text( ) != text )
			itemStatus = -1;
}

void widgetUI::PropertyPage::saveToFile(bool clicked) {
	saveToList(clicked);
	QFileInfo fInfo(this->currentFilePath);
	if( fInfo.exists( ) ) {
		QDir dirObj;
		QString targetDir = fInfo.absolutePath( ) + "/bak/";
		dirObj.mkpath(targetDir);
		const QString TargetFileName = targetDir + "/" + QDateTime::currentDateTime( ).toString("yyyy.MM.dd.hh.mm.ss.zzz") + '.' + fInfo.fileName( ) + ".bak";
		QFile::rename(this->currentFilePath, TargetFileName);
	}
	dXml::XmlDataDoc doc = appInstances::FileBuffSystem::fileInstance.getDocValue(currentFilePath);
	doc.save(this->currentFilePath);
}

void PropertyPage::translating(bool clicked) {
	MenuPage* menuPage = widgetUI::MainWindow::getMenuPage( );
	const QHash<int, QString>* translating = menuPage->getTranslating( );
	QVector<PropertyItem*> items = *itemArray;
	TranslatingToolPage* translatingToolPage = menuPage->translatingToolPage;
	if( menuPage->translatingFile.isEmpty( ) ) {
		const QString chars = appInstances::FileBuffSystem::fileInstance.getCurrentDir( );
		QFileInfo info(chars);
		QString fileName = info.fileName( );
		if( !fileName.endsWith(".xml") )
			fileName.append(".xml");
		menuPage->fileName->setText(fileName);
		menuPage->translatingFile = chars + "/" + fileName;
	}
	for( auto item : items ) {
		auto&& number = item->number->text( );
		int akey = number.toInt( );
		const QString value = translating->value(akey);
		if( value.isEmpty( ) ) {
			// 不存在则添加一个节点
			translatingToolPage->addItem(akey, item->Translation->text( ));
			continue;
		}
		// 设置当前控件
		item->Translation->setText(value);
		// 设置匹配 xml 节点
		QList<dXml::XmlDataUnit*>* list = xmlDataUnit->getChildrens( );
		QList<dXml::XmlDataUnit*>::iterator iterator = list->begin( );
		QList<dXml::XmlDataUnit*>::iterator end = list->end( );
		for( ;iterator != end;++iterator ) {
			dXml::XmlDataUnit* unit = *iterator;
			if( unit->nodeName( ).remove("node_") == number ) {
				unit->appendAttr(menuPage->translatingToolPage->getName( ), value);
				break;
			}
		}
	}
	saveToFileSystemBuff( );
	menuPage->allSave( );
}

void PropertyPage::removeItem(PropertyItem* item
	, bool clicked) {
	QWidget* widget = qobject_cast<QWidget*>(item);
	// 删除 xml 元素
	QList<dXml::XmlDataUnit*>* list = xmlDataUnit->getChildrens( );
	QList<dXml::XmlDataUnit*>::iterator iterator = list->begin( );
	QList<dXml::XmlDataUnit*>::iterator end = list->end( );
	for( ;iterator != end;++iterator ) {
		dXml::XmlDataUnit* unit = *iterator;
		if( unit->nodeName( ).remove("node_") == item->number->text( ) ) {
			unit->setParen(Q_NULLPTR);
			delete unit;
			break;
		}
	}
	// 删除ui元素
	mainLayout->removeWidget(widget);
	if( currentEditItem == widget ) {
		currentEditItem = Q_NULLPTR;
		ui.proEdit->clear( );
		ui.editName->clear( );
	}
	// 删除数组元素
	itemArray->removeOne(item);
	delete widget;
	// 存储到缓存

	saveToFileSystemBuff( );
}

void PropertyPage::editItem(PropertyItem* item
	, bool clicked) {
	if( currentEditItem != Q_NULLPTR )
		if( itemStatus == -1 ) {
			currentEditItem->status->setText("未保存 *");
			noSaveArray->append(currentEditItem);
			QString tarText = ui.proEdit->text( );
			QString removeZero = tarText.remove(removePreZero);
			if( removeZero.isEmpty( ) ) {
				currentEditItem->property->setText("0");
			} else
				currentEditItem->property->setText(removeZero);
		} else
			currentEditItem->status->setText("正常");
	ui.proEdit->setText(item->property->text( ));
	item->status->setText("正在编辑");
	ui.editName->setText(item->Translation->text( ) + "(" + item->number->text( ) + ")");
	ui.proEdit->setFocus( );
	if( currentEditItem != Q_NULLPTR )
		currentEditItem->editBtn->setChecked(false);
	currentEditItem = item;
	ui.infoName->setText(item->number->text( ));
}

PropertyPage::PropertyPage(QWidget* parent) : ATabPageBase(parent) {
	ui.setupUi(this);
	itemArray = new QVector<PropertyItem*>;
	noSaveArray = new QVector<PropertyItem*>;
	setObjectName(getName( ));
	initControl( );

	// test( );
}

PropertyPage::~PropertyPage( ) {
	delete this->xmlDataUnit;
	delete this->itemArray;
	delete this->noSaveArray;
}

void PropertyPage::emitSynInfo(bool clicked) {
	emit synInfo(clicked);
}

QString PropertyPage::getName( ) {
	static QString objName = nodeName;
	return objName;
}

QIcon PropertyPage::getIcon( ) {
	static QIcon icon = QApplication::style( )->standardIcon(( QStyle::StandardPixmap )30);
	return icon;
}

/*
PropertyPage* PropertyPage::getInstance( ) {
	static PropertyPage instance;
	return &instance;
}
*/
